package com.yulebaby.callsenter.database.manager;


import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.database.CallLogBeanDao;
import com.yulebaby.callsenter.database.CustomerBeanDao;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.ui.base.BaseBean;
import com.yulebaby.callsenter.utils.DateUtil;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Zhangbo
 * Time: 2016/11/25
 * 完成对Basebean表的具体操作
 */

public class Dao {
    private DaoManager manager;
    private static Dao mDao = new Dao();

    private Dao() {
        manager = DaoManager.getInstance();
    }

    public static Dao getInstance() {
        return mDao;
    }

    /**
     * 完成对数据库中bean 表的插入操作
     *
     * @param bean
     * @return
     */
    public boolean insertBean(BaseBean bean) {
        boolean flag = false;
        if (bean instanceof CallLogBean) {
            flag = manager.getDaoSession().getCallLogBeanDao().insertOrReplace((CallLogBean) bean) != -1 ? true : false;
        } else if (bean instanceof CustomerBean) {
            flag = manager.getDaoSession().getCustomerBeanDao().insertOrReplace((CustomerBean) bean) != -1 ? true : false;
        }
        manager.closeConnection();
        return flag;
    }

    /**
     * 插入多条记录，需要开辟新的线程
     *
     * @param beans
     * @return
     */
    public boolean insertMultCustomerBean(final List<CustomerBean> beans) {
        boolean flag = false;
        try {
            manager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (CustomerBean bean : beans) {
                        manager.getDaoSession().getCustomerBeanDao().insertOrReplace(bean);
                    }
                    manager.closeConnection();
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 插入多条记录，需要开辟新的线程
     *
     * @param beans
     * @return
     */
    public boolean insertMultCallLogBean(final List<CallLogBean> beans) {
        boolean flag = false;
        try {
            manager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (CallLogBean bean : beans) {
                        manager.getDaoSession().getCallLogBeanDao().insertOrReplace(bean);
                    }
                    manager.closeConnection();
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 完成对bean的某一条记录的修改
     *
     * @param bean
     * @return
     */
    public boolean updateBean(BaseBean bean) {
        boolean flag = false;
        try {
            if (bean instanceof CallLogBean) {
                manager.getDaoSession().getCallLogBeanDao().update((CallLogBean) bean);
            } else if (bean instanceof CustomerBean) {
                manager.getDaoSession().getCustomerBeanDao().update((CustomerBean) bean);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        manager.closeConnection();
        return flag;
    }

    /**
     * @param bean
     * @return
     */
    public boolean deleteBean(BaseBean bean) {
        boolean flag = false;
        try {
            if (bean instanceof CallLogBean) {
                manager.getDaoSession().getCallLogBeanDao().delete((CallLogBean) bean);
            } else if (bean instanceof CustomerBean) {
                manager.getDaoSession().getCustomerBeanDao().delete((CustomerBean) bean);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        manager.closeConnection();
        return flag;
    }


    /**
     * 删除所有记录
     */
    public void deleteAllBean(Class cls) {
        manager.getDaoSession().deleteAll(cls);
        manager.closeConnection();
    }

    /**
     * 返回所有记录
     *
     * @return
     */
    public List<BaseBean> listAll(Class cls) {
        List<BaseBean> list = manager.getDaoSession().loadAll(cls);
        manager.closeConnection();
        return list;
    }


    /**
     * 返回CallLog中所有未上传的CallBean的记录
     *
     * @return
     */
    public List<CallLogBean> listUnloadFailAll() {
        QueryBuilder<CallLogBean> builder = manager.getDaoSession().getCallLogBeanDao().queryBuilder();
        List<CallLogBean> list = builder.where(CallLogBeanDao.Properties.IsUpdate.eq(0)).list();
        manager.closeConnection();
        return list;
    }

    /**
     * 按照主键返回单行记录
     *
     * @param key
     * @return
     */
    public BaseBean listOneBean(Class cls, long key) {
        BaseBean callLogBean = (BaseBean) manager.getDaoSession().load(cls, key);
        manager.closeConnection();
        return callLogBean;
    }

    /**
     * 根据电话号码返回对应客户的Bean
     *
     * @param phoneNumOrName
     * @return
     */
    public CustomerBean queryBeanByPhone(String phoneNumOrName) {
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        CustomerBean customerBean;

        queryBuilder.where(queryBuilder.or(CustomerBeanDao.Properties.Phone.eq(phoneNumOrName),
                CustomerBeanDao.Properties.Spare_phone1.eq(phoneNumOrName),
                CustomerBeanDao.Properties.Spare_phone2.eq(phoneNumOrName),
                CustomerBeanDao.Properties.Customer_name.eq(phoneNumOrName)));
        List<CustomerBean> list = queryBuilder.list();
        // 防止号码重复后报错, 如果号码重复则使用第一个号码
        if (list.size() > 1) {
            customerBean = list.get(0);
        } else {
            customerBean = queryBuilder.unique();
        }
        manager.closeConnection();
        return customerBean;
    }

    /**
     * 根据呼叫时间返回对应客户的Bean
     *
     * @param callTime 呼叫时间
     * @return
     */
    public CallLogBean queryBeanByTime(Long callTime) {
        QueryBuilder<CallLogBean> queryBuilder = manager.getDaoSession().getCallLogBeanDao().queryBuilder();
        queryBuilder.where(CallLogBeanDao.Properties.Call_time.eq(callTime));
        CallLogBean calllogbean = queryBuilder.unique();
        manager.closeConnection();
        return calllogbean;
    }


    /**
     * 返回CallLogBean按照电话时间逆序排列
     *
     * @return
     */
    public List<CallLogBean> listCallLogDesAll() {
        List<CallLogBean> callLogBeanList = manager.getDaoSession().getCallLogBeanDao().queryBuilder().orderDesc(CallLogBeanDao.Properties.Call_time).list();
        manager.closeConnection();
        return callLogBeanList == null ? new ArrayList<CallLogBean>() : callLogBeanList;
    }


    /**
     * 返回CallLogBean按照电话时间逆序排列
     *
     * @return
     */
    public List<CallLogBean> listCallLogDesHavePath() {
        QueryBuilder<CallLogBean> queryBuilder = manager.getDaoSession().getCallLogBeanDao().queryBuilder();
        List<CallLogBean> callLogBeanList = queryBuilder.where(queryBuilder.and(CallLogBeanDao.Properties.File_path.isNotNull(), CallLogBeanDao.Properties.File_path.notEq(""))).orderDesc(CallLogBeanDao.Properties.Call_time).list();
        manager.closeConnection();
        return callLogBeanList == null ? new ArrayList<CallLogBean>() : callLogBeanList;
    }

    /**
     * 数据库查询未签约客户列表
     *
     * @return
     */
    public List<CustomerBean> listCustomerBySaler() {
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        List<CustomerBean> customerBeanList = queryBuilder.where(
                queryBuilder.and(CustomerBeanDao.Properties.Alloc_time.isNotNull(),
                        queryBuilder.or(CustomerBeanDao.Properties.Stage.eq(Constant.Stage.CLIENTCONFIRM),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.NEWINROOM),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.COMMUNICATION),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.VISITED))))
                .orderDesc(CustomerBeanDao.Properties.Alloc_time).list();
        manager.closeConnection();
        return customerBeanList == null ? new ArrayList<CustomerBean>() : customerBeanList;
    }

    /**
     * 数据库查询未签约客户列表
     *
     * @return
     */
    public List<CustomerBean> listCustomerByImportent() {
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        List<CustomerBean> customerBeanList = queryBuilder.where(
                queryBuilder.and(CustomerBeanDao.Properties.StressIntent.isNotNull(),
                        CustomerBeanDao.Properties.Alloc_time.isNotNull(),
                        queryBuilder.or(CustomerBeanDao.Properties.Stage.eq(Constant.Stage.CLIENTCONFIRM),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.NEWINROOM),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.COMMUNICATION),
                                CustomerBeanDao.Properties.Stage.eq(Constant.Stage.VISITED))))
                .orderAsc(CustomerBeanDao.Properties.StressIntent).list();
        manager.closeConnection();
        return customerBeanList == null ? new ArrayList<CustomerBean>() : customerBeanList;
    }

    /**
     * 数据库查询即将投公海的列表
     *
     * @return
     */
    public List<CustomerBean> listCustomerByDays() {
        long preTime = DateUtil.stringToLong(DateUtil.getPre7Date());
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        List<CustomerBean> customerBeanList =
                queryBuilder.where(
                        queryBuilder.and(CustomerBeanDao.Properties.Last_contact_time.isNotNull(),
                                CustomerBeanDao.Properties.Last_contact_time.ge(preTime),
                                queryBuilder.or(CustomerBeanDao.Properties.Stage.eq(Constant.Stage.CLIENTCONFIRM),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.NEWINROOM),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.COMMUNICATION),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.VISITED))))
                        .orderAsc(CustomerBeanDao.Properties.Last_contact_time).list();

        if (customerBeanList != null && customerBeanList.size() > 0) {
            for (CustomerBean customerBean : customerBeanList) {
                String smdate = DateUtil.formatDateTime(customerBean.getLast_contact_time());
                String bDate = DateUtil.getCurrentDate();
                customerBean.setDay_number(DateUtil.daysBetween(smdate, bDate));
            }
        }
        manager.closeConnection();
        return customerBeanList == null ? new ArrayList<CustomerBean>() : customerBeanList;
    }

    /**
     * 数据库查询即将近期回访的列表
     *
     * @return
     */
    public List<CustomerBean> listCustomerByReturn() {
        long nowTime = DateUtil.stringToLong(DateUtil.getCurrentDate());
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        List<CustomerBean> customerBeanList =
                queryBuilder.where(
                        queryBuilder.and(CustomerBeanDao.Properties.Visit_date.ge(nowTime),
                                CustomerBeanDao.Properties.Visit_date.isNotNull(),
                                queryBuilder.or(CustomerBeanDao.Properties.Stage.eq(Constant.Stage.CLIENTCONFIRM),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.NEWINROOM),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.COMMUNICATION),
                                        CustomerBeanDao.Properties.Stage.eq(Constant.Stage.VISITED))))
                        .orderAsc(CustomerBeanDao.Properties.Visit_date).list();
        manager.closeConnection();
        return customerBeanList == null ? new ArrayList<CustomerBean>() : customerBeanList;
    }

    /**
     * 获取最大的Update时间
     *
     * @return
     */
    public Long getUpdateTime() {
        QueryBuilder<CustomerBean> queryBuilder = manager.getDaoSession().getCustomerBeanDao().queryBuilder();
        List<CustomerBean> customerBeanList = queryBuilder.orderDesc(CustomerBeanDao.Properties.Update_time).list();
        manager.closeConnection();
        if (customerBeanList != null && customerBeanList.size() > 0) {
            return customerBeanList.get(0).getUpdate_time() == null ? 0l : customerBeanList.get(0).getUpdate_time();
        } else {
            return 0l;
        }
    }
}
